<template>
  <a-tree-select
    v-model="innerValue"
    :tree-data="categoryTreeList"
    :placeholder="placeholder"
    :treeDefaultExpandAll="false"
    :selectFlag="selectFlag"
    @change=""
  >
  </a-tree-select>
</template>
<script>
import { getAction } from '../../api/manage'

export default {
  props: {
    value: [String],
    placeholder: [String],
    selectFlag: {
      type: Boolean,
      default: false,
      require: false
    }
  },
  watch: {
    value(newVal) {
      this.innerValue = newVal
    },
    innerValue(newVal) {
      this.$emit('input', newVal)
      this.$emit('selectCategory', newVal)
    }
  },
  created() {
    this.initCategoryTree()
  },
  data() {
    return {
      categoryTreeList: [],
      innerValue: undefined,
      url: {
        getCategoryTree: '/product/category/getCategoryTree'
      }
    }
  },
  methods: {
    /**
     * 初始化分类树 数据
     */
    initCategoryTree() {
      this.cardLoading = true
      getAction(this.url.getCategoryTree).then(res => {
        if (res.success) {
          this.categoryTreeList = res.result
          this.addDisabledForNodesWithChildren(this.categoryTreeList)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.cardLoading = false
      })
    },
    findNode(list, nodeId) {
      for (let item of list) {
        if (item.key == nodeId) {
          return item.children == null
        }
        if (item.children && item.children.length > 0) {
          let result = this.findNode(item.children, nodeId)
          if (result) {
            return result.children == null
          }
        }
        return null
      }
    },
    addDisabledForNodesWithChildren(nodes) {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          node.selectable = false
          this.addDisabledForNodesWithChildren(node.children)
        }
      })
    }
  }
}
</script>